package com.forum.service.impl;

import com.forum.mapper.UserMapper;
import com.forum.pojo.User;
import com.forum.service.UserService;
import com.forum.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Mirror
 * @CreateDate 2020/3/22.
 * 用户业务处理实现类
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据多个用户id查询用户名字 （业务理解错误，该方法暂时无用）
     * @param uids
     * @return
     */
    public List<String> queryNamesByUids(List<Long> uids){
        List<User> users = this.userMapper.selectByIdList(uids);
        return users.stream().map(user -> user.getUserName()).collect(Collectors.toList());
    }

    /**
     * 根据用户ID查询用户信息
     * @param uid
     * @return
     */
    @Override
    public User queryUserByUid(Long uid) {
        User user = this.userMapper.selectByPrimaryKey(uid);
        user.setUserPassword(null);
        return user;
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public Boolean register(User user) {
        //使用MD5工具类进行密码加密
        user.setUserPassword(MD5Utils.md5(user.getUserPassword()));
        //设置用户类型 ：普通用户
        user.setUserStatus(2);
        return this.userMapper.insertSelective(user) == 1;
    }

    /**
     * 根据用户名 and 用户密码查询用户
     * @param username
     * @param password
     * @return
     */
    @Override
    public User userLogin(String username, String password) {
        // 查询
        User record = new User();
        record.setUserName(username);
        User user = this.userMapper.selectOne(record);
        // 校验用户名
        if (user == null) {
            return null;
        }
        // 校验密码
        if (!user.getUserPassword().equals(MD5Utils.md5(password))) {
            return null;
        }
        user.setUserPassword("");
        // 用户名密码都正确
        return user;
    }
}
